package com.joplus.housekeeper.adapter;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.Time;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hyphenate.chatuidemo.DemoApplication;
import com.hyphenate.chatuidemo.ui.ChatActivityNew;
import com.hyphenate.easeui.controller.EaseUI;
import com.joplus.housekeeper.R;
import com.joplus.housekeeper.bean.ChatPastBean;
import com.joplus.housekeeper.bean.XmppMessage;
import com.joplus.housekeeper.bean.XmppUser;
import com.joplus.housekeeper.network.RequestHelper;
import com.joplus.housekeeper.network.TextCallback;
import com.joplus.housekeeper.utils.Imageutils;
import com.joplus.housekeeper.utils.RealmHelper;
import com.joplus.housekeeper.utils.StringUtils;
import com.joplus.housekeeper.utils.T;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import io.realm.RealmResults;

/**
 * Created by zisheng on 2017/9/19.
 */

class ChatCalendarGvAdapter extends BaseAdapter {

    private LayoutInflater layout;
    private int monthCount;
    private int lostDay;
    private int block;
    private Context context;
    Calendar calendar;

    private final SimpleDateFormat monthFormat;
    private final SimpleDateFormat yearFormat;
    private final String ym;
    private List<Integer> hasRecords;
    private String accountId;

    public ChatCalendarGvAdapter(Context context, Calendar calendar) {
        this.context = context;
        layout = LayoutInflater.from(context);
        // calendar.add(Calendar.DAY_OF_MONTH, 1);
        this.calendar = calendar;
        monthCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        Date time = calendar.getTime();
        Date localTime = new Date();
        monthFormat = new SimpleDateFormat("MM");
        yearFormat = new SimpleDateFormat("yyyy");
        SimpleDateFormat dayFormat = new SimpleDateFormat("dd");


        if (monthFormat.format(localTime).equals(monthFormat.format(time))) {
            lostDay = Integer.valueOf(dayFormat.format(localTime));
        }

        Calendar clone = (Calendar) calendar.clone();
        clone.set(Calendar.DAY_OF_MONTH, 1);
        block = clone.get(Calendar.DAY_OF_WEEK) - 2;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        ym = format.format(calendar.getTime());
    }

    public ChatCalendarGvAdapter(Context context, Calendar calendar, List<Integer> strings, String accountId) {
        this.context = context;
        layout = LayoutInflater.from(context);
        // calendar.add(Calendar.DAY_OF_MONTH, 1);
        this.calendar = calendar;
        this.accountId = accountId;
        monthCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        Date time = calendar.getTime();
        Date localTime = new Date();
        monthFormat = new SimpleDateFormat("MM");
        yearFormat = new SimpleDateFormat("yyyy");
        SimpleDateFormat dayFormat = new SimpleDateFormat("dd");


        if (monthFormat.format(localTime).equals(monthFormat.format(time))) {
            lostDay = Integer.valueOf(dayFormat.format(localTime));
        }

        Calendar clone = (Calendar) calendar.clone();
        clone.set(Calendar.DAY_OF_MONTH, 1);
        block = clone.get(Calendar.DAY_OF_WEEK) - 2;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        ym = format.format(calendar.getTime());
        hasRecords = strings;
    }

    @Override
    public int getCount() {
        return monthCount + block + 1;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    Holder holder;
    boolean canClick = false;

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = layout.inflate(R.layout.item_day, null);
            holder = new Holder(convertView);
            convertView.setTag(holder);
        }
        holder = (Holder) convertView.getTag();


        if (position > block) {
            if (hasRecords != null) {
                if (hasRecords.contains(position - block)) {
                    holder.tv1.setTextColor(context.getResources().getColor(R.color.jo_text_red));
                    holder.tv1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            T.showShort(context, ym + "-" + (position - block));

                            RequestHelper.getInstance().CheckMessages(context, ym + "-" + (position - block), accountId, new TextCallback() {
                                @Override
                                public void onFailure(String responseString) {
                                }

                                @Override
                                public void onSuccess(Object responseString) {
                                    ChatPastBean chatPastBean = (ChatPastBean) responseString;
                                    if (!chatPastBean.getCode().equals("2000")) {
                                        /*Intent intent = new Intent(context, ChatActivityNew.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("userId", DemoApplication.getInstance().getJid());
                                        intent.putExtras(bundle);
                                        context.startActivity(intent);*/
                                        return;
                                    }
                                    try {
                                        String messageId = checkDb(chatPastBean);
                                        DemoApplication.getInstance().setMessageId(messageId);
                                        Intent intent = new Intent(context, ChatActivityNew.class);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("userId", DemoApplication.getInstance().getJid());
                                        intent.putExtras(bundle);
                                        context.startActivity(intent);
                                    } catch (Exception e) {
                                        Log.e("calenader--------------", "exception: " + e.toString());
                                        T.showShort(context, "出现了不可预知的错误");
                                    }


                                }
                            });
                        }
                    });

                } else {
                    holder.tv1.setTextColor(context.getResources().getColor(R.color.text_66));

                }
            }
            holder.tv2.setText(" ");
            holder.tv1.setText(position - block + "");

        }
        ;


        return convertView;
    }

    private String checkDb(ChatPastBean chatPastBean) throws UnsupportedEncodingException {
        Gson gson = new Gson();
        String jid = DemoApplication.getInstance().getJid();
        XmppMessage firstMessage = gson.fromJson(chatPastBean.getData().get(0).getBody(), XmppMessage.class);
        RealmResults<XmppMessage> message = RealmHelper.instance().findMessage(firstMessage.getMessageId());
        if (message != null && message.size() > 0) {
            return firstMessage.getMessageId();
        }
        String messageId = "";
        for (int i = 0; i < chatPastBean.getData().size(); i++) {

            XmppMessage xmppMessage = new Gson().fromJson(chatPastBean.getData().get(i).getBody(), XmppMessage.class);
            if (i == 0) {
                messageId = xmppMessage.getMessageId();
            }
            saveMessage(xmppMessage, chatPastBean.getData().get(i).getFrom().getResource() != null ? 1 : 0
            );
        }

        return messageId;


    }

    private void saveMessage(XmppMessage xmppMessage, int i) throws UnsupportedEncodingException {
        RealmHelper.instance().beginTran();
        if (xmppMessage.getType().equals("3")) {

            Bitmap bitmap = base64ToBitmap(xmppMessage.getContent());
            File file = Imageutils.savePic(bitmap);
            xmppMessage.setContent(file.getAbsolutePath());
            xmppMessage.setDirect(i);
            xmppMessage.setMessageDateTime(System.currentTimeMillis());


        } else if (xmppMessage.getType().equals("2")) {

            File skRoot = Environment.getExternalStorageDirectory();
            String voiceFileName = getVoiceFileName("customer-service1");
            String filePath = skRoot.getAbsolutePath() + "/voice/" + voiceFileName;
            base642File(xmppMessage.getContent(), skRoot.getAbsolutePath() + "/voice/" + voiceFileName);
            xmppMessage.setContent(filePath);
            xmppMessage.setDirect(i);
            xmppMessage.setMessageDateTime(System.currentTimeMillis());


        } else {
            final byte[] decode = Base64.decode(xmppMessage.getContent(), Base64.DEFAULT);
            String content = new String(decode, "UTF-8");

            xmppMessage.setContent(content);
            xmppMessage.setDirect(i);
            xmppMessage.setMessageDateTime(System.currentTimeMillis());


        }

        XmppUser xmppUser = RealmHelper.instance().findUser(DemoApplication.getInstance().customerJid).get(0);
        RealmHelper.instance().insertNewMessage(xmppUser, xmppMessage);
    }

    public Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    private String getVoiceFileName(String uid) {
        Time now = new Time();
        now.setToNow();
        return uid + now.toString().substring(0, 15) + ".amr";
    }


    public void base642File(String code, String path) {

        byte[] buffer = Base64.decode(code, Base64.DEFAULT);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(path);
            out.write(buffer);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class Holder {
        public Holder(View view) {
            tv1 = (TextView) view.findViewById(R.id.tv_1);
            tv2 = (TextView) view.findViewById(R.id.tv_2);
            ll_bg = (LinearLayout) view.findViewById(R.id.ll_bg);
        }

        private TextView tv1;
        private TextView tv2;
        private LinearLayout ll_bg;
    }
}
